package jdbc_util;

import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

public class Conn_Close {
    private   static Properties p= new Properties();
    private    static  ThreadLocal<Connection> tl=new ThreadLocal<Connection>();
    static{
        InputStream inputStream = Conn_Close.class.getClassLoader().getResourceAsStream("jdbc.properties");
        try {
            p.load(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static  Connection getConnection(){
        Connection connection = tl.get();
        if (connection==null){
            try {
                Class.forName(p.getProperty("driver"));
                connection= DriverManager.getConnection(p.getProperty("url"),p.getProperty("username"),p.getProperty("password"));
                tl.set(connection);
                return  connection;
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return connection;
    }

    //关闭资源
    public static void close(Connection conn, PreparedStatement pstmt, ResultSet rs){
        try {
            if(rs!=null){
                rs.close();
            }
            if(pstmt!=null){
                pstmt.close();
            }
            if(conn!=null){
                conn.close();tl.remove();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

}
